package com.ruoyi.tj.controller;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.servlet.MultipartProperties;
import org.springframework.util.unit.DataSize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@RestController
public class UploadController {

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    MultipartProperties multipartProperties;

    @PostMapping("/api/upload")
    @ResponseBody
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            /*long size = file.getSize();

            if(size > multipartProperties.getMaxFileSize().toBytes()) {
                return AjaxResult.error("超出文件上传大小限制，限制:" + multipartProperties.getMaxFileSize().toMegabytes()+"MB");
            }
            */

            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            Map<String, Object> data = new HashMap<>();
            data.put("url", url);
            data.put("fileName", fileName);
            data.put("newFileName", FileUtils.getName(fileName));
            data.put("originalFilename", file.getOriginalFilename());
            return AjaxResult.success(data);
        }
        catch (Throwable e)
        {
            /*if(e.getMessage().indexOf("Maximum upload size exceeded") != -1) {
                return AjaxResult.error("超出文件上传大小限制，限制:" + multipartProperties.getMaxFileSize().toMegabytes()+"MB");
            }*/
            return AjaxResult.error(e.getMessage());
        }
    }

}
